package org.xtlgen;

import java.util.ArrayList;

/**
 * Adapter to make an ArrayList work as a Circular list
 */
public class CircularList<E> {
  /**
   * Builds an empty list.
   */
  public CircularList() {
    this.list = new ArrayList<E>();
  }
  
  /**
   * Builds an empty list with the given initialCapacity.
   */
  public CircularList(int initialCapacity) {
    this.list = new ArrayList<E>(initialCapacity);
  }
  
  /**
   * Obtain the number of elements on this list.
   *
   * @return the number of elements on this list.
   */
  public int size() {
    return this.list.size();
  }
  
  /**
   * Get the indexth element on this list.
   *
   * @param index the requested index.
   *
   * @return the requested element.
   */
  public E get(int index) {
    int size = size();
    int realIndex = (index % size);
    if (realIndex < 0) {
      realIndex = size + realIndex;
    }
    return this.list.get(realIndex);
  }
  
  /**
   * Add the given element to this list.
   *
   * @param elem the new element.
   */
  public void add(E elem) {
    this.list.add(elem);
  }

  /**
   * Get the underlying ArrayList.
   *
   * @return the list.
   */
  ArrayList<E> getList() {
    return list;
  }

  /*
   * Fields
   */
  private ArrayList<E> list;
}
  
